
package numberporting.bean;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Hashtable;
import javax.ws.rs.WebApplicationException;
import numberporting.service.*;

public class CustomerStore implements ICustomerStore {
    private Hashtable<String,Customer> customers;
    
    public CustomerStore(){
        customers = new Hashtable<String,Customer>();
    }
    public void saveToFile(){
        this.saveToFile("./customerstore.dat");
    }
    public void loadFromFile(){
        this.loadFromFile("./customerstore.dat");
    }
    public void saveToFile(String filename){
        try {
            ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(filename));
            os.writeObject(this.customers);
            os.close();
        } catch (Exception e) {
           e.printStackTrace();        
        }
    }
    public void loadFromFile(String filename){
        try{
            ObjectInputStream is = new ObjectInputStream(new FileInputStream(filename));
            this.customers = (Hashtable<String,Customer>) is.readObject();
            is.close();
        } catch(Exception e){
            e.printStackTrace();
        }
    }
    public void addCustomer(Customer customer){
        customers.put(customer.getId(), customer);
    }
    public void deleteCustomer(String customerId){
        customers.remove(customerId);
    }
    public Customer getCustomer(String customerId){
        return customers.get(customerId);
    }
    public void updateCustomer(Customer customer){
        customers.put(customer.getId(),customer);        
    }
    public boolean customerExists(String customerId){
        return (customers.get(customerId) != null);
    }
    public void checkCustomer(String customerId) throws InvalidCustomerException{
        if(!customerExists(customerId))
            throw new InvalidCustomerException("No such customer found (id:"+customerId+")");
    }
    // todo: wieso kann ich hier keine exception mitgeben?
    public void checkCustomerRS(String customerId) throws WebApplicationException{
        if(!customerExists(customerId))
            throw new WebApplicationException();
    }
}
